package com.hanhai.zrb.api.biz.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hanhai.common.file.fastdfs.service.IStorageClientService;
import com.hanhai.zrb.api.biz.dao.mybatis.PhotoDao;
import com.hanhai.zrb.api.biz.service.PhotoService;
import com.hanhai.zrb.model.photo.Photo;

@Service("photoService")
public class PhotoServiceImpl implements PhotoService {

	private Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private IStorageClientService storageClientService;
	
	@Resource
	private PhotoDao photoDao;
	
	@Override
	public List<Photo> getPhotoListByProjectId(Long id) {
		return photoDao.getPhotoListByProjectId(id);
	}

	@Override
	public List<Photo> getPhotoListByFundId(Long id) {
		return photoDao.getPhotoListByFundId(id);
	}
	
	@Override
	public Long add(Photo photo) {
		photoDao.add(photo);
		return photo.getId();
	}

	@Override
	public List<Photo> topBannerList() {
		List<Photo> list=photoDao.topBannerList();
		return list;
	}

	@Override
	public PageInfo bannerListPage(Integer pageNo, Integer pageSize) {
		if(pageNo==null){
			pageNo=1;
		}
		if(pageSize==null){
			pageSize=20;
		}
		PageHelper.startPage(pageNo, pageSize);
		List<Photo> list=photoDao.bannerListPage();
		PageInfo pageInfo = new PageInfo(list);
		return pageInfo;
	}

	@Override
	public void remove(Long id) {
		photoDao.remove(id);		
	}

	@Override
	public void update(Photo photo) {
		if(photo.getId() == null){
			logger.error("The is is null.");
			return;
		}
		photoDao.update(photo);
		
	}

	@Override
	public void addBanner(Photo photo) {
		Long id = photo.getId();
		if(id != null){
			Photo dbPhoto=photoDao.get(id);
			String dbUrl = dbPhoto.getUrl();
			String newUrl = photo.getUrl();	
			photoDao.update(photo);
			//更新了url,需要删除旧的
			if(dbUrl != null && !dbUrl.equals(newUrl)){
				ProjectServiceImpl.deleteInFastdfs(storageClientService, dbUrl);
			}
		}else{
			photoDao.add(photo);
		}		
		deleteRecentPhoto();			
	}

	private void deleteRecentPhoto() {
		//删除1天之前的临时图片，放在了这个位置
		List<Photo> list=photoDao.listRecentTempPhoto();
		if(list != null){
			for(Photo photo:list){
				photoDao.delete(photo.getId());
				ProjectServiceImpl.deleteInFastdfs(storageClientService, photo.getUrl());
			}
		}
	}

}
